package com.bird.component.database.config

import cn.dev33.satoken.stp.StpUtil
import com.baomidou.mybatisplus.annotation.DbType
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor
import com.bird.component.lang.util.log
import com.bird.component.lang.util.nonnull
import org.apache.ibatis.reflection.MetaObject
import org.mybatis.spring.annotation.MapperScan
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import java.time.LocalDateTime


@Configuration
class MyBatisPlusConfiguration {
    /**
     * 添加分页插件
     */
    @Bean
    fun mybatisPlusInterceptor(): MybatisPlusInterceptor {
        val interceptor = MybatisPlusInterceptor()
        interceptor.addInnerInterceptor(PaginationInnerInterceptor(DbType.MYSQL)) // 如果配置多个插件, 切记分页最后添加
        // 如果有多数据源可以不配具体类型, 否则都建议配上具体的 DbType
        return interceptor
    }

    @Bean
    fun myMetaObjectHandler(): MyMetaObjectHandler {
        return MyMetaObjectHandler()
    }
}

class MyMetaObjectHandler : MetaObjectHandler {
    override fun insertFill(metaObject: MetaObject) {
        log.info("开始插入填充...")
        this.strictInsertFill(
            metaObject, "createTime",
            LocalDateTime::class.java, LocalDateTime.now()
        )
        this.strictInsertFill(
            metaObject, "updateTime",
            LocalDateTime::class.java, LocalDateTime.now()
        )
        val loginId =if ( StpUtil.isLogin()) StpUtil.getLoginId() as? Long else null
        if (loginId.nonnull()) {
            this.strictInsertFill(
                metaObject, "createBy",
                Long::class.java,loginId
            )
            this.strictInsertFill(
                metaObject, "updateBy",
                Long::class.java, loginId
            )
        }
    }

    override fun updateFill(metaObject: MetaObject) {
        log.info("开始更新填充...")
        this.strictUpdateFill(
            metaObject, "updateTime",
            LocalDateTime::class.java, LocalDateTime.now()
        )
        val loginId =if ( StpUtil.isLogin()) StpUtil.getLoginId() as? Long else null
        if (loginId.nonnull()) {
            this.strictInsertFill(
                metaObject, "updateBy",
                Long::class.java, loginId
            )
        }
    }
}
